<?php

namespace App\Http\Controllers\Api;

use App\Events\UserRegistered;
use App\Handlers\ImageUploadHandler;
use App\Http\Requests\Api\SocialAuthorizationRequest;
use App\Http\Requests\Api\SocialLoginSecondRequest;
use App\Http\Requests\Api\WechatRegisterRequest;
use App\Models\PowerLog;
use App\Models\Sms;
use App\Models\User;
use App\Models\Wallet;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

/**
 * @title 第三方登录
 * @description 接口说明
 */

class SocialController extends ApiController
{
    /**
     * @title 微信登录(新)
     * @description {socail_type}默认为weixin,如果code=412,跳转至绑定手机号页面
     * @author wjx
     * @url /api/{social_type}/socialStore
     * @method POST
     *
     * @param name:access_token type:string require:1 default: other: desc:微信access_token
     * @param name:openID type:string require:1 default: other: desc:openid
     *
     * @return accessToken:accessToken
     * @return refreshToken:refreshToken
     * @return atExpiredTime:atExpiredTime
     * @return rtExpiredTime:rtExpiredTime
     * @return user_id:user_id
     * @return phone:phone
     * @return hasPwd:hasPwd
     * @return hasPhone:hasPhone
     * @return hasPayPwd:hasPayPwd
     *
     */

    public function socialStore($type, SocialAuthorizationRequest $request)
    {
        if (!in_array($type, ['weixin'])) {
            return $this->failed('请使用微信登录');
        }
        $driver = \Socialite::driver($type);

        try {
            $token = $request->access_token;
            if ($type == 'weixin') {
                $driver->setOpenId($request->openID);
            }

            $oauthUser = $driver->userFromToken($token);
            $user_info = $oauthUser->user;

        } catch (\Exception $e) {
            return $this->failed('参数错误，未获取用户信息');
        }
        switch ($type) {
            case 'weixin':
                $unionid = $oauthUser->offsetExists('unionid') ? $oauthUser->offsetGet('unionid') : null;
                if ($unionid) {
                    $user = User::where('weixin_unionid', $unionid)->first();
                } else {
                    $user = User::where('weixin_openid', $oauthUser->getId())->first();
                }
                // 没有用户，让去绑定手机号
                if (!$user) {
                    return response()->json([
                        'code' => 412,
                        'msg' => '请先绑定手机号',
                    ]);
                }

                // 没有手机号，去绑定手机号
                if (!$user->phone) {
                    return response()->json([
                        'code' => 412,
                        'msg' => '请先绑定手机号',
                    ]);
                } else {
                    $user->accessToken = strtolower(str_random(64));
                    $user->refreshToken = strtolower(str_random(64));
                    $user->atExpiredTime = Carbon::now()->addHours(2); //俩小时
                    $user->rtExpiredTime = Carbon::now()->addDays(7); //七天
                    $user->save();

                    return $this->success([
                        'accessToken' => $user->id . '.' . $user->accessToken,
                        'refreshToken' => $user->id . '.' . $user->refreshToken,
                        'atExpiredTime' => $user->atExpiredTime->toDateTimeString(),
                        'rtExpiredTime' => $user->rtExpiredTime->toDateTimeString(),
                        'user_id' => $user->id,
                        'phone' => $user->phone,
                        'hasPwd' => $user->hasPwd,
                        'hasPhone' => $user->hasPhone,
                        'hasPayPwd' => $user->hasPayPwd,
                    ]);
                }

                break;
        }
    }
    /**
     * @title 绑定手机号(新)
     * @description 接口说明
     * @author wjx
     * @url /api/wechat_register
     * @method POST
     *
     * @param name:access_token type:string require:1 default: other: desc:微信access_token
     * @param name:openID type:string require:1 default: other: desc:openid
     * @param name:unionID type:string require:1 default: other: desc:unionid
     * @param name:phone type:string require:1 default: other: desc:手机号
     * @param name:sms_code type:string require:1 default: other: desc:短信验证码
     * @param name:key type:string require:1 default: other: desc:验证key
     * @param name:captcha type:string require:1 default: other: desc:图片验证码
     *
     * @return accessToken:accessToken
     * @return refreshToken:refreshToken
     * @return atExpiredTime:atExpiredTime
     * @return rtExpiredTime:rtExpiredTime
     * @return phone:phone
     * @return hasPwd:hasPwd
     * @return hasPhone:hasPhone
     * @return hasPayPwd:hasPayPwd
     */
    public function wechat_register(WechatRegisterRequest $request, ImageUploadHandler $uploader)
    {
        $type = 'weixin';
        $phone = $request->phone;
        $sms_code = $request->sms_code;
        $unionid = $request->unionID;
        $check_sms = $this->checkSmsCode($phone, $sms_code);
        if ($check_sms !== true) {
            return $this->failed($check_sms['message']);
        }
        $has_user = User::where('phone', $phone)->first();

        $driver = \Socialite::driver($type);
        try {
            $token = $request->access_token;
            if ($type == 'weixin') {
                $driver->setOpenId($request->openID);
            }

            $oauthUser = $driver->userFromToken($token);
            $user_info = $oauthUser->user;

        } catch (\Exception $e) {
            return $this->failed('参数错误，未获取用户信息');
        }
        // base64_encode(file_get_contents($user_info['headimgurl']));
        if ($has_user) {
            $has_user->hasPhone = 1;
            $has_user->weixin_openid = $user_info['openid'];
            $has_user->weixin_unionid = $user_info['unionid'];
            $has_user->weixin_nickname = $user_info['nickname'];
            $has_user->weixin_avatar = $user_info['headimgurl'];
            $has_user->city = $user_info['city'];
            $has_user->country = $user_info['country'];
            $has_user->province = $user_info['province'];
            $has_user->language = $user_info['language'];
            $has_user->sex = $user_info['sex'];
            $has_user->accessToken = strtolower(str_random(64));
            $has_user->refreshToken = strtolower(str_random(64));
            $has_user->atExpiredTime = Carbon::now()->addHours(2); //俩小时
            $has_user->rtExpiredTime = Carbon::now()->addDays(7); //七天
        } else {
            $new_user = new User();
            $new_user->phone = $phone;
            $new_user->weixin_openid = $user_info['openid'];
            $new_user->weixin_unionid = $user_info['unionid'];
            $new_user->weixin_nickname = $user_info['nickname'];
            $new_user->weixin_avatar = $user_info['headimgurl'];
            $new_user->city = $user_info['city'];
            $new_user->country = $user_info['country'];
            $new_user->province = $user_info['province'];
            $new_user->language = $user_info['language'];
            $new_user->sex = $user_info['sex'];
            $new_user->nickname = $user_info['nickname'];
            $new_user->avatar = $user_info['headimgurl'];
            $new_user->status = User::STATUS_ABLED;
            $new_user->code = $this->str_rand();
            $new_user->regType = 2;
            $new_user->hasPwd = 0;
            $new_user->hasPhone = 1;
            $new_user->hasPayPwd = 0;
            $new_user->accessToken = strtolower(str_random(64));
            $new_user->refreshToken = strtolower(str_random(64));
            $new_user->atExpiredTime = Carbon::now()->addHours(2); //俩小时
            $new_user->rtExpiredTime = Carbon::now()->addDays(7); //七天
        }

        DB::beginTransaction();
        try {
            if ($has_user) {
                $has_user->save();
                $return_user = $has_user;
            } else {
                $new_user->save();
                $return_user = $new_user;
                event(new UserRegistered($new_user->id));
            }

            DB::commit();

            return $this->success([
                'accessToken' => $return_user->id . '.' . $return_user->accessToken,
                'refreshToken' => $return_user->id . '.' . $return_user->refreshToken,
                'atExpiredTime' => $return_user->atExpiredTime->toDateTimeString(),
                'rtExpiredTime' => $return_user->rtExpiredTime->toDateTimeString(),
                'user_id' => $return_user->id,
                'phone' => $return_user->phone,
                'hasPwd' => $return_user->hasPwd,
                'hasPhone' => $return_user->hasPhone,
                'hasPayPwd' => $return_user->hasPayPwd,
            ]);

        } catch (\Exception $exception) {
            DB::rollBack();
            return $this->failed('绑定失败');
        }
    }

    public function bindPhoneFirst(SocialLoginRequest $request, ImageUploadHandler $uploader)
    {
        $phone = $request->phone;
        $sms_code = $request->sms_code;
        $unionid = $request->unionID;
        $has_user = User::where('phone', $phone)->first();
        $wx_user = User::where('weixin_unionid', $unionid)->first()->toArray();
        if (!$wx_user) {
            return $this->failed('unionID参数错误');
        }
        $res = Sms::where('phone', $phone)->orderBy('id', 'desc')->first();
        if ($sms_code !== $res->code) {
            return $this->failed('短信验证码错误');
        }

        if (!$has_user) {
            return response()->json([
                'code' => 413,
                'msg' => '请设置登录和支付密码',
            ]);
        }
        $has_user->hasPhone = 1;
        $has_user->weixin_openid = $wx_user['weixin_openid'];
        $has_user->weixin_unionid = $wx_user['weixin_unionid'];
        $has_user->weixin_nickname = $wx_user['weixin_nickname'];
        $has_user->weixin_avatar = $wx_user['weixin_avatar'];
        $has_user->city = $wx_user['city'];
        $has_user->country = $wx_user['country'];
        $has_user->province = $wx_user['province'];
        $has_user->language = $wx_user['language'];
        $has_user->sex = $wx_user['sex'];
        $has_user->accessToken = strtolower(str_random(64));
        $has_user->refreshToken = strtolower(str_random(64));
        $has_user->atExpiredTime = Carbon::now()->addHours(2); //俩小时
        $has_user->rtExpiredTime = Carbon::now()->addDays(7); //七天

        DB::beginTransaction();
        try {
            $has_user->save();
            User::destroy($wx_user->id);

            DB::commit();
            return $this->success([
                'accessToken' => $has_user->id . '.' . $has_user->accessToken,
                'refreshToken' => $has_user->id . '.' . $has_user->refreshToken,
                'atExpiredTime' => $has_user->atExpiredTime->toDateTimeString(),
                'rtExpiredTime' => $has_user->rtExpiredTime->toDateTimeString(),
                'user_id' => $has_user->id,
                'phone' => $has_user->phone,
                'hasPwd' => $has_user->hasPwd,
                'hasPhone' => $has_user->hasPhone,
                'hasPayPwd' => $has_user->hasPayPwd,
            ]);

        } catch (\Exception $exception) {

            DB::rollBack();
            return $this->failed('绑定失败');
        }
    }

    public function bindPhoneSecond(SocialLoginSecondRequest $request, ImageUploadHandler $uploader)
    {
        $phone = $request->phone;
        $sms_code = $request->sms_code;
        $unionid = $request->unionID;
        $check_sms = $this->checkSmsCode($phone, $sms_code);
        if ($check_sms !== true) {
            return $this->failed($check_sms['message']);
        }
        $wx_user = User::where('weixin_unionid', $unionid)->first();
        if (!$wx_user) {
            return $this->failed('unionID参数错误');
        }
        $wx_user->phone = $phone;
        $wx_user->password = bcrypt($request->password);
        $wx_user->security = bcrypt($request->security);
        $wx_user->regType = 2;
        $wx_user->hasPwd = 1;
        $wx_user->hasPhone = 1;
        $wx_user->hasPayPwd = 1;
        $wx_user->accessToken = strtolower(str_random(64));
        $wx_user->refreshToken = strtolower(str_random(64));
        $wx_user->atExpiredTime = Carbon::now()->addHours(2); //俩小时
        $wx_user->rtExpiredTime = Carbon::now()->addDays(7); //七天
        DB::beginTransaction();
        try {
            $wx_user->save();
            event(new UserRegistered($wx_user->id));

            DB::commit();

            return $this->success([
                'accessToken' => $wx_user->id . '.' . $wx_user->accessToken,
                'refreshToken' => $wx_user->id . '.' . $wx_user->refreshToken,
                'atExpiredTime' => $wx_user->atExpiredTime->toDateTimeString(),
                'rtExpiredTime' => $wx_user->rtExpiredTime->toDateTimeString(),
                'user_id' => $wx_user->id,
                'phone' => $wx_user->phone,
                'hasPwd' => $wx_user->hasPwd,
                'hasPhone' => $wx_user->hasPhone,
                'hasPayPwd' => $wx_user->hasPayPwd,
            ]);
        } catch (\Exception $exception) {

            DB::rollBack();
            return $this->failed('绑定失败');
        }
    }
    /**
     * 生成邀请码
     *
     * @return void
     * @Description
     * @author wjx
     */
    public function str_rand()
    {
        $str = mt_rand(100000, 999999);
        $count = User::where('code', $str)->count();
        if ($count > 0) {
            return $this->str_rand();
        } else {
            return $str;
        }
    }
    /**
     * @title 绑定微信提现账户
     * @description {socail_type}默认为weixin
     * @author wjx
     * @url /api/{social_type}/bind_wechat
     * @method POST
     * @module 新手任务
     *
     * @header name:accessToken require:1 default: desc:用户token
     *
     *
     * @param name:access_token type:string require:1 default: other: desc:微信access_token
     * @param name:openID type:string require:1 default: other: desc:openid
     * @param name:unionID type:string require:1 default: other: desc:unionid
     *
     * @return weixin_withdraw_nickname:微信昵称
     * @return user_id:用户ID
     *
     */
    public function bind_wechat($type, Request $baserequest, SocialAuthorizationRequest $request)
    {
        $user = $baserequest->user;
        if (!in_array($type, ['weixin'])) {
            return $this->failed('请选择微信');
        }
        $driver = \Socialite::driver($type);

        try {
            $token = $request->access_token;
            if ($type == 'weixin') {
                $driver->setOpenId($request->openID);
            }

            $oauthUser = $driver->userFromToken($token);
            $user_info = $oauthUser->user;

        } catch (\Exception $e) {
            return $this->failed('参数错误，未获取用户信息');
        }

        switch ($type) {
            case 'weixin':
                if (!$user->weixin_withdraw_openid) {
                    Wallet::update_power($user->id, 10, 1);
                    PowerLog::add_log($user->id, 4, 10, 1);
                }
                $user->weixin_withdraw_openid = $user_info['openid'];
                $user->weixin_withdraw_unionid = $user_info['unionid'];
                $user->weixin_withdraw_nickname = $user_info['nickname'];
                $user->weixin_withdraw_avatar = $user_info['headimgurl'];

                $user->save();
                return $this->success([
                    'weixin_withdraw_nickname' => $user->weixin_withdraw_nickname,
                    'user_id' => $user->id,
                ]);
                break;

            default:

                break;
        }
    }

}
